package com.base.dp;

public class MinPathSum {
    public static void main(String[] args) {
        MinPathSum minPathSum = new MinPathSum();
        System.out.println(minPathSum.minPathSum(new int[][]{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}));
    }

    private int minPathSum(int[][] nums) {
        int m = nums.length;
        int n = nums[0].length;
        // dp[i][j]表示到达i,j的最小路径和
        int[][] dp = new int[m][n];
        dp[0][0] = nums[0][0];
        // 1 0
        // 1 1
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i > 0 && j > 0) {
                    dp[i][j] = Math.min(dp[i - 1][j],dp[i][j - 1]) + nums[i][j];
                } else if (i == 0 && j > 0) {
                    dp[i][j] = dp[i][j - 1] + nums[i][j];
                } else if (i > 0) {
                    dp[i][j] = dp[i - 1][j] + nums[i][j];
                }
            }
        }
        return dp[m - 1][n - 1];
    }
}
